import { Component, OnInit, Input } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Observable } from 'rxjs';
import { ApiService } from '@srvs/api.service';

@Component({
  selector: 'edit-site',
  templateUrl: './edit-site.component.html',
  styles: [`
    :host ::ng-deep .form-inner {
      padding: 16px 40px 0;
    }
    :host ::ng-deep .label-width {
      width: 81px;
    }
  `]
})
export class EditSiteComponent implements OnInit {

  public validateForm: FormGroup;

  @Input() public data: any;
  @Input() public companies: any = [];

  constructor(
    private formBuilder: FormBuilder,
    private apiSrv: ApiService
  ) { }

  public ngOnInit(): void {
    const data: any = this.data || {};

    this.validateForm = this.formBuilder.group({
      siteName: [data.siteName || null, [Validators.required, Validators.minLength(2), Validators.maxLength(20)]],
      siteCode: [data.siteCode || null, [Validators.required, Validators.minLength(2), Validators.maxLength(20)]],
      companyId: [data.companyId || null, [Validators.required]],
      isValid: [data.isValid !== undefined ? data.isValid : null, [Validators.required]],
      description: [data.description || null]
    });
  }

  public hasError(controlName: string): boolean {
    return !!(
      this.validateForm.get(controlName).dirty &&
      this.validateForm.get(controlName).errors
    );
  }

  public submit(): Observable<any> {
    for (const item in this.validateForm.controls) {
      this.validateForm.controls[item].markAsDirty();
      this.validateForm.controls[item].updateValueAndValidity();
    }

    if (this.validateForm.valid) {
      const apiSites: string = '/api/sites',
        params: any = Object.assign({}, this.validateForm.value);

      if (this.data) {
        params.id = this.data.id;
        return this.apiSrv.put(apiSites, params);
      } else {
        return this.apiSrv.post(apiSites, params);
      }

    } else {
      return new Observable(observer => observer.complete());
    }
  }

}
